import { createSignal, createEffect, onCleanup } from 'solid-js';
import { DownloadTask } from '@/types/download';
import { getDownloads, addDownload as addDownloadApi, pauseDownload as pauseDownloadApi, resumeDownload as resumeDownloadApi, cancelDownload as cancelDownloadApi } from '@/lib/api/download';

const [downloads, setDownloads] = createSignal<DownloadTask[]>([]);

// 初始化时获取下载列表
createEffect(async () => {
  try {
    const downloadList = await getDownloads();
    setDownloads(downloadList);
  } catch (error) {
    console.error('获取下载列表失败:', error);
  }
});

export const useDownloadsStore = () => {
  // 设置每秒更新一次下载列表的定时器
  const intervalId = setInterval(async () => {
    try {
      const updatedList = await getDownloads();
      setDownloads(updatedList);
    } catch (error) {
      console.error('定时更新下载列表失败:', error);
    }
  }, 1000); // 1000毫秒 = 1秒

  // 组件卸载时清除定时器
  onCleanup(() => clearInterval(intervalId));

  const activeDownloads = () => downloads().filter(item => 
    ['downloading', 'paused', 'queued', 'completed', 'installing'].includes(item.status)
  );

  const completedDownloads = () => downloads().filter(item => 
    ['installed', 'error'].includes(item.status)
  );

  const addDownload = async (category: string, pkgname: string, filename: string, name: string) => {
    try {
      await addDownloadApi(category, pkgname, filename, name);
      const updatedList = await getDownloads();
      setDownloads(updatedList);
    } catch (error) {
      console.error('添加下载任务失败:', error);
    }
  };

  const pauseDownload = async (category: string, pkgname: string) => {
    try {
      await pauseDownloadApi(category, pkgname);
      const updatedList = await getDownloads();
      setDownloads(updatedList);
    } catch (error) {
      console.error('暂停下载任务失败:', error);
    }
  };

  const resumeDownload = async (category: string, pkgname: string) => {
    try {
      await resumeDownloadApi(category, pkgname);
      const updatedList = await getDownloads();
      setDownloads(updatedList);
    } catch (error) {
      console.error('继续下载任务失败:', error);
    }
  };

  const cancelDownload = async (category: string, pkgname: string) => {
    try {
      await cancelDownloadApi(category, pkgname);
      const updatedList = await getDownloads();
      setDownloads(updatedList);
    } catch (error) {
      console.error('取消下载任务失败:', error);
    }
  };

  return {
    downloads,
    activeDownloads,
    completedDownloads,
    addDownload,
    pauseDownload,
    resumeDownload,
    cancelDownload
  };
};